import { Button, Card, message, Popconfirm, Popover, Table, Tag } from 'antd';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

import sysJobLogService from '@/api/services/stars/sysJobLogService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { SearchForm } from './search-form';
import { ScheduleType } from './type';

import { ListData } from '#/entity';
import { JobGroupTypeMapText } from '#/publicVariable';

export default function Log() {
  const { id } = useParams();
  const [searchForm, setSearchForm] = useState<SearchForm>({
    take: 10,
    page: 1,
  });
  const [tableData, setTableData] = useState<ListData<ScheduleType>>();
  const getLogList = () => {
    sysJobLogService.LogList(id, { ...searchForm }).then((res) => {
      setTableData(res);
    });
  };
  useEffect(() => {
    getLogList();
  }, [searchForm]);
  const columns = [
    {
      fixed: 'left' as const,
      title: '任务名称',
      dataIndex: 'jobName',
      width: 90,
    },
    {
      width: 90,
      title: '任务组名',
      dataIndex: 'jobGroup',
      render: (_, record) => {
        return JobGroupTypeMapText[record.jobGroup];
      },
    },
    {
      width: 140,
      title: '调用目标字符串',
      dataIndex: 'invokeTarget',
    },
    {
      title: '执行信息',
      dataIndex: 'exceptionInfo',
      render: (exceptionInfo) => (
        <Popover content={<div style={{ width: 800 }}>{exceptionInfo}</div>} title="执行信息">
          <span>
            {exceptionInfo?.length > 55 ? `${exceptionInfo?.slice(0, 55)}...` : exceptionInfo}
          </span>
        </Popover>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center' as const,
      width: 90,
      render: (status) => {
        if (status === '0') {
          return <Tag color="success">成功</Tag>;
        }
        return <Tag color="error">失败</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      width: 200,
      render: (createAt) => {
        return datetime(createAt);
      },
    },
    {
      fixed: 'right' as const,
      title: <div style={{ marginRight: '20px' }}>操作</div>,
      align: 'right' as const,
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('QUARTZ:SYS_JOB:DELETE') && (
            <Popconfirm
              title={`确定要删除在 <${datetime(record.createAt)}> 创建的 <${
                record.jobName
              }> 日志吗？`}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                // 删除一个日志
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];
  const onClearAll = () => {
    // 删除所有日志
    sysJobLogService.logClearAll().then((res) => {
      if (res > 0) {
        message.success('删除成功');
      }
      setSearchForm({ take: 10, page: 1 });
    });
  };
  const onDelete = (record) => {
    // 删除一个日志
    console.log(record);

    if (tableData?.data.length === 1 && tableData?.count !== 1) {
      sysJobLogService.logDelete(record.jobLogId!).then((res) => {
        if (res > 0) {
          message.success('删除成功');
        }
        setSearchForm({ page: searchForm.page - 1, take: searchForm.take });
      });
    } else {
      sysJobLogService.logDelete(record.jobLogId!).then((res) => {
        if (res > 0) {
          message.success('删除成功');
        }
        setSearchForm({ ...searchForm });
      });
    }
  };

  return (
    <Card
      extra={
        <div>
          {hasPermission('QUARTZ:SYS_JOB:DELETE') && (
            <Popconfirm
              title="确定要删除所有日志吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onClearAll();
              }}
              placement="left"
            >
              <Button type="primary">清空日志</Button>
            </Popconfirm>
          )}
        </div>
      }
    >
      <Table
        size="small"
        rowKey="jobLogId"
        dataSource={tableData?.data}
        columns={columns}
        pagination={{
          current: searchForm.page,
          pageSize: searchForm.take,
          total: tableData?.count, // 新增：总条目数
          // showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, size) => {
            setSearchForm((prev) => ({ ...prev, page, take: size }));
          },
        }}
      />
    </Card>
  );
}
